<template>
    <div class="userInfoContainer">
        <el-form ref="form" :model="shopFrom" label-width="80px">
            <el-form-item label="店铺封面">
                <img class="avatar" :src="shopFrom.cover">
                <br>更改头像
                <input type="file" @input="upFile($event)">
            </el-form-item>

            <el-form-item label="店铺名">
            <el-input v-model="shopFrom.name"></el-input>
            </el-form-item>

            <el-form-item label="店主">
                <!-- 搜索框 -->
                <el-input v-model="shopName" @change="searchUsers" placeholder="搜索用户"></el-input>
            </el-form-item>

            <div class="search">
                    <button v-for="(item,index) in userList" class="searchText" @click="setUserId(item.id,item.name)" >{{ item.name }}</button>
            </div>
            <br>
            <el-form-item label="店铺简介">
                <el-input v-model="shopFrom.description"></el-input>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="addAndUpdate">{{operation}}</el-button>
                <el-button @click="reset">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import{selectUserById,addUser,updateUser,selectUsersByName} from '@/api/user'
import fileStore  from '@/api/fileStore';
import shop from '@/api/shop';
export default {
    data(){
        return {
            id:null,
            shopFrom:{
                id:'',
                name:'',
                owner:'',
                password:'',
                description:'',
                cover:''
            },
            userinfo:'',
            shopName:'',
            userList:'',
            operation:''
        }
    },
    created() {
      //初始化 
      this.init();
    },
    methods: {
      //初始化用户
      init() {
          //当前页面是否携带id,带id查询出值
          if(this.$route.params && this.$route.params.id) {
              this.id  = this.$route.params.id;
              this.shopFrom.id = this.id;
              this.operation="修改"
              this.getShop();
          } else { //路径没有id值
              //清空表单
              this.operation="创建"
              this.reset()
          }
      },
      //模糊查询用户
      searchUsers(){
        selectUsersByName(this.shopName)
            .then(response=>{
                this.userList = response.data.list;
            })
      },
      //设置所有者id
      setUserId(id,name){
        this.shopFrom.owner = id;
        this.shopName = name;
        this.userList="";
        console.log(this.shopFrom.owner);
      },
      //获取商店
      getShop(){
        shop.getShopById(this.id)
            .then(response=>{
                this.shopFrom = response.data.shop;
                selectUserById(this.shopFrom.owner)
                    .then(response=>{
                        this.userinfo = response.data.user;
                        this.setUserId(this.userinfo.id,this.userinfo.name);
                    })
            })
      },
      //修改和添加商店
      addAndUpdate(){
        if(!this.checkForm()){
            return;
        }
        if(this.shopFrom.id){
            //修改
            shop.update(this.shopFrom)
                .then(response=>{
                        this.$message({
                            message: '修改成功',
                            type: 'success'
                        });
                    this.reset();
                    this.$router.push({path:'/shop/list'})
                })
        }else{
            //增加
            shop.add(this.shopFrom)
                .then(response=>{
                        this.$message({
                            message: '添加成功',
                            type: 'success'
                        });
                    this.reset();
                    this.$router.push({path:'/shop/list'})
                })
        }
      },
      //上传文件检查
      checkFile(file) {
        var reg = new RegExp(".*\\.(jpg|jpeg|png|gif|bmp|svg)$");
        const isJPG = reg.test(file.name);
        const isLt2M = file.size / 1024 / 1024 < 10;
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG/png/gif 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 10MB!');
        }
        return isJPG && isLt2M;
      },
      //检查数据
      checkForm(){
        if(this.shopFrom.name.length >= 1 && this.shopFrom.owner.length >=1){
            return true;
        }
        this.$message('店铺名和店长为必须');
        return false;
      },
      //加载文件
      loadFile(file){
        return new Promise((success)=>{
            //读取文件流
            var reader = new FileReader();
            var binData=null;
            let data = reader.readAsArrayBuffer(file);
            reader.addEventListener('load',(e=>{
                binData = new Blob([e.target.result],{type:file.type});
                success(binData);
            }));
        })
      },
      //上传文件
      async upFile(event){
        var file = event.target.files[0];
        if(!this.checkFile(file)){
            return;
        }
        var binData = await this.loadFile(file);
        //封装文件
        var upload = new FormData();
        //参数名 文件 文件名
        upload.append('file',binData,file.name);
        fileStore.upLoadFile(upload)
            .then(response=>{
                console.log(typeof this.shopFrom.cover);
                //上传文件后检查头像是否已经存在
                if(this.shopFrom.cover == response.data.file.url){
                    this.$message.success('更换成功');
                    return;
                }
                if(this.shopFrom.cover.length > 1){
                    console.log(this.shopFrom.cover);
                    fileStore.deleteFile(this.shopFrom.cover)
                        .then(response=>{
                            this.$message.success('更换成功');
                        })
                }
                this.shopFrom.cover = response.data.file.url;
            })
      },
      //重置条件
      reset(){
        this.shopFrom.name='';
        this.shopFrom.cover='';
        this.shopFrom.owner='';
        this.shopFrom.description='';
        this.shopName="";
        this.shopFrom.id = this.id;
      }
    }
}
</script>
<style>
.userInfoContainer {
    margin-top: 10%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
.search{
    position: relative;
    bottom: 10px;
    left: 40%;
    margin-top: -20px;
    width: 200px;
    /* display: none; */
}
.searchText{
    display: block;
    width: 150px;
    height: 20px;
    border: none;
    border-bottom: 1px solid rgb(130, 195, 233);
    outline: none;
}

.searchText:hover{
    background-color: rgb(103, 173, 235);
    color: white;
}
</style>